package com.aliyun.solutions.demo.wanxiang.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * 登录
 *
 * @author solution
 * @date 2024/12/04
 */
@Slf4j
@Validated
@Controller
public class LoginController {

    @Value("${USER_NAME:''}")
    private String systemUsername;
    @Value("${USER_PASSWORD:''}")
    private String systemPassword;

    @Value("${SECURITY_ENABLED:false}")
    private boolean securityEnabled;

    @Autowired
    private HttpServletRequest request;

    @GetMapping("/login")
    public String login(Model model) {
        return "login";
    }

    @RequestMapping("/login")
    public ResponseEntity<String>  submit(@RequestParam(required = false) String username,
                                          @RequestParam(required = false) String password, Model model) {
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            if (StringUtils.equals(systemUsername, username) && StringUtils.equals(DigestUtils.md5DigestAsHex(systemPassword.getBytes(StandardCharsets.UTF_8)), password)) {
                request.getSession(true).setAttribute("logined", true);
                return ResponseEntity.status(HttpStatus.FOUND).header("Location", "/index").build();
            }
        }
        model.addAttribute("username", username);
        model.addAttribute("password", password);
        model.addAttribute("message", "登录失败，请输入正确的账号信息！");

        return ResponseEntity.status(HttpStatus.FOUND).header("Location", "/login?error=1").build();
    }

    @GetMapping(value = {"/", "/index", "/index.html"})
    public String index() {
        if(!securityEnabled){
            return "index";
        }
        Boolean logined = (Boolean) request.getSession(true).getAttribute("logined");
        if (logined == null || !logined) {
            return "redirect:/login";
        }
        return "index";
    }
}